package com.jxchexie.signin;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.utils.TimeUtils;
import com.jxchexie.api.Api;
import com.jxchexie.app.App;
import com.jxchexie.model.MyMessage;
import com.jxchexie.utils.JsonUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Response;


public class UploadImageActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageView iv_img;
    private Button bt_camera;
    private Button bt_xiangce;
    private static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果
    /* 临时图片名称 */
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    private File tempFile;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_image);
        initPhotoError();
        initView();
    }
    //iv_img
    private void initView() {
        iv_img = (ImageView) findViewById(R.id.temp_img);
        bt_camera = (Button) findViewById(R.id.bt_camera);
        bt_xiangce = (Button) findViewById(R.id.bt_xiangce);
        //从SharedPreferences获取图片
        getBitmapFromSharedPreferences();
        bt_camera.setOnClickListener(this);
        bt_xiangce.setOnClickListener(this);
    }
    // android 7.0以上系统解决拍照的问题
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void initPhotoError(){
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_camera:
                // 激活相机
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                // 判断存储卡是否可以用，可用进行存储
                if (hasSdcard()) {
                    tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
                     //从文件中创建uri
                    Uri uri = Uri.fromFile(tempFile);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);//设置存放路径
                }
                // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
                startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
                break;
            case R.id.bt_xiangce:
                // 激活系统图库，选择一张图片
                Intent intent1 = new Intent(Intent.ACTION_PICK);
                intent1.setType("image/*");
                // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
                startActivityForResult(intent1, PHOTO_REQUEST_GALLERY);
                break;
        }
    }


    /*
     * 判断sdcard是否被挂载
     */
    private boolean hasSdcard() {
        //判断ＳＤ卡手否是安装好的　　　media_mounted
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }
    /**
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PHOTO_REQUEST_GALLERY) {
            // 从相册返回的数据
            if (data != null) {
                // 得到图片的全路径
                Uri uri = data.getData();
                //crop(uri);
                /**
                 *
                 */
                Bitmap bitmap = openImage(uri);
                /**
                 * 获得图片
                        */
                iv_img.setImageBitmap(bitmap);
                //保存到SharedPreferences
                saveBitmapToSharedPreferences(bitmap);
            }
        } else if (requestCode == PHOTO_REQUEST_CAREMA) {
            // 从相机返回的数据
            if (hasSdcard()) {
                /**
                 * 获得图片
                 */
                // 激活系统图库，选择一张图片
                Intent intent1 = new Intent(Intent.ACTION_PICK);
                intent1.setType("image/*");
                // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
                startActivityForResult(intent1, PHOTO_REQUEST_GALLERY);
            }
            else {
                Toast.makeText(this, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    //保存图片到SharedPreferences
    //处理上传前的图片
    private void saveBitmapToSharedPreferences(Bitmap bitmap) {
        // Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        //第一步:将Bitmap压缩至字节数组输出流ByteArrayOutputStream
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
        //第二步:利用Base64将字节数组输出流中的数据转换成字符串String
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        String imageString = new String(Base64.encodeToString(byteArray, Base64.DEFAULT));
        //第三步:将String保持至SharedPreferences
        SharedPreferences sharedPreferences = getSharedPreferences("testSP", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("image", imageString);
        editor.commit();
        //上传图片
        saveToInternet(imageString,"");
    }
    /**
     * 上传图片到服务器
     */
    private void saveToInternet(String imgStr, String imgName) {
        //上传单个图片
        /*获得当前登录用户的用户名*/
        String user_name = App.getInstance().getUser(UploadImageActivity.this);
        /*显示提示正在登录对话框*/
        final MaterialDialog md = new MaterialDialog.Builder(this)
                .title("提示")
                .content("图片正在上传，请稍等...")
                .progress(true, 0)
                .show();
        //获取上传时候的时间
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd-HH时-mm分-ss秒 ");
        String str_Date= TimeUtils.getCurTimeString(sdf);
        //构造请求体
        HashMap<String, String> params = new HashMap<>();
        params.put("time",str_Date);
        params.put("user_name", user_name);
        params.put("image", imgStr);

        JSONObject jsonObject = new JSONObject(params);
        OkGo.<String>post(Api.UPLOAD_IMAGE)
                .tag(this)//通过这个tag可以取消这个操作
                .upJson(jsonObject.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        //关闭提示框
                        md.dismiss();
                        MyMessage ms = new MyMessage();
                        ms = JsonUtils.fromJson(s,MyMessage.class);
                        Toast.makeText(UploadImageActivity.this, ms.getStatus(), Toast.LENGTH_SHORT).show();
                        //Toast.makeText(UploadImageActivity.this, ms.getMsg(), Toast.LENGTH_SHORT).show();
                        //Log.v("zj",ms.getMsg());
                    }
                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        md.dismiss();
                        Toast.makeText(UploadImageActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                        super.onError(call, response, e);
                    }
                });
    }
    /**
     * 从shared Preference获取图片
     */
    private void getBitmapFromSharedPreferences(){
            SharedPreferences sharedPreferences = getSharedPreferences("testSP", Context.MODE_PRIVATE);
            //第一步:取出字符串形式的Bitmap
            String imageString = sharedPreferences.getString("image", "");
            //第二步:利用Base64将字符串转换为ByteArrayInputStream
            byte[] byteArray = Base64.decode(imageString, Base64.DEFAULT);
            if (byteArray.length == 0) {
                iv_img.setImageResource(R.drawable.camera);
            } else {
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);

                //第三步:利用ByteArrayInputStream生成Bitmap
                Bitmap bitmap = BitmapFactory.decodeStream(byteArrayInputStream);
                iv_img.setImageBitmap(bitmap);
            }
        }
    /**
     * 将本地图片转成Bitmap
     * @param uri 已有图片的路径
     * @return bitmap resource
     */
    public Bitmap openImage(Uri uri){
        Bitmap bitmap = null;
        try{
           bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri);
        }catch(IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }
}
